/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Menu;
import cn.net.ecode.modules.sys.entity.Module;
import cn.net.ecode.modules.sys.service.MenuService;
import cn.net.ecode.modules.sys.service.ModuleService;
import cn.net.ecode.modules.sys.utils.UserUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 菜单管理Controller
 * 
 * @author ThinkGem
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/menu")
public class MenuController extends BaseController {

	@Autowired
	private MenuService menuService;
	@Autowired
	private ModuleService moduleService;

	@ModelAttribute
	public Menu get(String menuCode, boolean isNewRecord) {
		return menuService.get(menuCode, isNewRecord);
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = {"list", ""})
	public String list(Menu menu, Model model) {
		return "modules/sys/menuList";
	}
	
	@RequiresPermissions("sys:menu:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public List<Menu> listData(Menu menu) {
		if (StringUtils.isBlank(menu.getParentCode())) {
			menu.setParentCode(Menu.ROOT_CODE);
		}
		List<Menu> list = null;
		if (StringUtils.isNotBlank(menu.getMenuCode())) {
			list = Lists.newArrayList(get(menu.getMenuCode(), false));
		} else {
			list = menuService.findList(menu);
		}
		return list;
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = "form")
	public String form(Menu menu, Model model) {
		if (menu.getParent() != null && StringUtils.isNotBlank(menu.getParent().getMenuCode())) {
			menu.setParent(menuService.get(menu.getParent().getMenuCode()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(menu.getMenuCode())) {
				Menu menuChild = new Menu();
				menuChild.setParent(new Menu(menu.getParent().getMenuCode()));
				List<Menu> list = menuService.findList(menu);
				if (list.size() > 0) {
					menu.setSorts(list.get(list.size() - 1).getSorts());
					if (menu.getSorts() != null) {
						menu.setSorts(menu.getSorts() + 30);
					}
				}
			}
		}
		if (menu.getSorts() == null) {
			menu.setSorts(30);
		}
		model.addAttribute("menu", menu);
		Module module = new Module();
		module.setStatus(Module.STATUS_NORMAL);
		model.addAttribute("moduleList", moduleService.findList(module));
		return "modules/sys/menuForm";
	}

	@RequiresPermissions("sys:menu:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Menu menu) {
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, menu)) {
			return renderResult(Global.FALSE, message);
		}
		menuService.save(menu);
		return renderResult(Global.TRUE, "保存菜单'" + menu.getName() + "'成功！");
	}

	@RequiresPermissions("sys:menu:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(Menu menu, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		if (!menu.getCurrentUser().isSuperAdmin()){
			return renderResult(Global.FALSE, "越权操作，只有超级管理员才能修改此数据！");
		}
		menuService.delete(menu);
		return renderResult(Global.TRUE, "删除菜单成功！");
	}

	/**
	 * 返回树JSON数据
	 * @param extCode
	 * @param isShowHide
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String extCode, String isShowHide, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Menu> list = menuService.findList(new Menu());
		for (int i = 0; i < list.size(); i++) {
			Menu e = list.get(i);
			if (StringUtils.isBlank(extCode) || (extCode != null && !extCode.equals(e.getMenuCode()) && !e.getParentCodes().contains("," + extCode + ","))) {
				if (isShowHide != null && isShowHide.equals("0") && e.getIsShow().equals("0")) {
					continue;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getMenuCode());
				map.put("pId", e.getParentCode());
				map.put("pIds", e.getParentCodes());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}

	/**
	 * 批量修改菜单排序
	 */
	@RequiresPermissions("sys:menu:edit")
	@ResponseBody
	@RequestMapping(value = "updateSorts")
	public String updateSorts(String[] ids, Integer[] sorts, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		if (!UserUtils.getUser().isSuperAdmin()){
			return renderResult(Global.FALSE, "越权操作，只有超级管理员才能修改此数据！");
		}
		for (int i = 0; i < ids.length; i++) {
			Menu menu = new Menu(ids[i]);
			menu.setSorts(sorts[i]);
			menuService.updateSorts(menu);
		}
		return renderResult(Global.TRUE, "保存菜单排序成功！");
	}

	// //////////////////////////////////////

	/**
	 * 导航树（原平台）
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "tree")
	public String tree() {
		return "modules/sys/menuTree";
	}

	/**
	 * 菜单选择树（无框架页时显示调用）
	 * @param parentId
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "treeselect")
	public String treeselect(String parentId, Model model) {
		model.addAttribute("parentId", parentId);
		return "modules/sys/menuTreeselect";
	}

	@RequiresPermissions("sys:menu:edit")
	@ResponseBody
	@RequestMapping(value = "dataFix")
	public String dataFix(){
		menuService.updateFixParentCodes();
		return renderResult(Global.TRUE, "数据修复成功");
	}

}
